package com.jushu.storbox.actions;

import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.ExceptionConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.ShareInfo;
import com.huawei.sharedrive.sdk.android.modelV2.request.SharedUserV2;
import com.huawei.sharedrive.sdk.android.serviceV2.ShareClientV2;

/**
 * 
 * Share deal class
 * 
 */
public class ShareActions extends Actions {

	private static final String TAG = ShareActions.class.getSimpleName();
	
	private final static int FROMINODE = 1002;
	
	public ShareActions(Context context) {
		super(context);
	}

	/**
	 * 
	 * batch share
	 * @param getContext()
	 * @param service
	 * @param exceptionHandler
	 * @param putShareRequest
	 * @param shareInfo
	 * @throws ClientException
	 */
	public void batchShare(ICloudDriveService service,Handler exceptionHandler,
			List<SharedUserV2> putShareRequest, ShareInfo shareInfo) throws ClientException {
		String tag = ShareActions.this.getClass().toString();
		LogUtil.i(tag, "batchShare[Actions]");
		if (!checkToken(service, exceptionHandler)) {
			return;
		}
		ShareClientV2.getInstance().batchAddShareResource(
				ShareDriveApplication.getInstance().getAuthorization(),
				putShareRequest, shareInfo);
	}

	public void getShareResourceFromServer(
			FileFolderInfo shareInfos,
			String folderId, ICloudDriveService service,
			Handler eHandler, Handler aHandler, int dir) {
		LogUtil.i(TAG, "getShareResourceFromServer[Actions]");
		if (ShareDriveApplication.getInstance().
				getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), aHandler);
				} catch (ClientException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					handleException(eHandler, e1,
							ClientConfig.SENDFROMLOGIN, null);// 1001
					return;
				}
			}

			try {
				List<FileFolderInfo> shareResource = service
						.getServerShareResourceList(getContext(), "DESC", folderId,
								shareInfos.getOwnerBy(), "modifiedAt");
				Message msg = new Message();
				msg.obj = shareResource;
				msg.what = dir;
				aHandler.sendMessage(msg);
				
				LogUtil.i(TAG, "getShareResourceFromServer success[Actions]");
			} catch (ClientException e) {
				// TODO: handle exception
				handleException(eHandler, e,
						ClientConfig.SENDFROMGETSHARERESOURCE, shareInfos);
				LogUtil.e(TAG,
						"getShareResourceFromServer fail:" + e.getStatusCode());
			}
		} else {
			handleException(eHandler, null,
					ClientConfig.SENDFROMGETSHARERESOURCE, null);
		}
	}
	
	/**
	 * delete inode file or folder
	 * @param getContext()
	 * @param service
	 * @param ehandler
	 * @param aHandler
	 * @param fileId
	 * @param item
	 * @return
	 */
	public String deleteINodeFileOrFolder(
			ICloudDriveService service, Handler ehandler,
			Handler aHandler, FileFolderInfo sharedItemInfo) {
		LogUtil.i(TAG, "deleteINodeFileOrFolder[Actions]");
		String info = null;
		if (ShareDriveApplication.getInstance().
				getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), aHandler);
				} catch (ClientException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					handleException(ehandler, e1,
							ClientConfig.INODEDELETEFILEORFOLDERLOGINFAIL, null);// 1001
					return info;
				}
			}

			try {
				service.deleteInodeFileOrFolder(sharedItemInfo.getId(),
						sharedItemInfo.getOwnerBy());
				service.rejectShare(ShareDriveApplication.getInstance()
						.getAuthorization(), Long.parseLong(sharedItemInfo
						.getOwnerBy()), Long.parseLong(sharedItemInfo
						.getiNodeId()));
				LogUtil.i(TAG, "deleteINodeFileOrFolder success[Actions]");
				Message message = new Message();
				message.what = 1;
				Bundle bundle = new Bundle();
				bundle.putSerializable("sharedItemInfo", sharedItemInfo);
				message.setData(bundle);
				aHandler.sendMessage(message);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				Message message = new Message();
				message.what = 2;
				aHandler.sendMessage(message);
				e.printStackTrace();
			} catch (ClientException e) {
				// TODO Auto-generated catch block
				LogUtil.e(TAG,
						"deleteINodeFileOrFolder fail:" + e.getStatusCode());
				e.printStackTrace();
				handleException(ehandler, e,
						ClientConfig.INODEDELETEFILEORFOLDERLOGINFAIL, null);
			}
		}
		return info;
	}

	public void getBaseShareResourceFromServer(
			ICloudDriveService service,
			Handler eHandler, Handler aHandler,
			int dir) {
		LogUtil.i(TAG, "getBaseShareResourceFromServer[Actions]");
		if (ShareDriveApplication.getInstance().
				getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), aHandler);
				} catch (ClientException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					handleException(eHandler, e1,
							ClientConfig.SENDFROMLOGIN, null);// 1001
					return;
				}
			}

			try {
				List<FileFolderInfo> shareResource = service.getBaseServerShareResourceList("0",
						ShareDriveApplication.getInstance().getWnerID(),
						"DESC", 1000, 0, "modifiedAt");
				Message msg = new Message();
				msg.obj = shareResource;
				msg.what = dir;
				msg.arg2 = FROMINODE;
				aHandler.sendMessage(msg);
				
				
				LogUtil.i(TAG,
						"getBaseShareResourceFromServer success[Actions]");
			} catch (ClientException e) {
				handleException(eHandler, e,
						ClientConfig.SENDFROMGETSHAREBASERESOURCE, null);
				LogUtil.e(
						TAG,
						"getBaseShareResourceFromServer fail:"
								+ e.getStatusCode());
			}
		} else {
			handleException(eHandler, null,
					ClientConfig.SENDFROMGETSHAREBASERESOURCE, null);
		}
	}

	/**
	 * @param getContext()
	 * @param service
	 * @param ehandler
	 * @param aHandler
	 * @param parentFileId
	 * @param fileFolderInfo
	 * @return
	 */
	public String shareCopyFile(ICloudDriveService service,
			Handler ehandler, Handler aHandler,
			FileFolderInfo innerParent,
			FileFolderInfo shaerFileFolderInfo) {
		String info = null;
		if (ShareDriveApplication.getInstance().
				getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), aHandler);
				} catch (ClientException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					return info;
				}
			}

			try {
				
				service.copyFile(shaerFileFolderInfo, innerParent);
				
				Message copyMsg = new Message();
				copyMsg.what = 3;
				copyMsg.obj = innerParent;
				aHandler.sendMessage(copyMsg);
			} catch (ClientException e) {
				handleException(ehandler, e, ClientConfig.TARGETFILESUCCESS, null);
				e.printStackTrace();
			}
		}
		return info;
	}

	/**
	 * @param getContext()
	 * @param service
	 * @param ehandler
	 * @param aHandler
	 * @param parentFileId
	 * @param fileFolderInfo
	 * @return
	 */
	public String shareCopyFolder(ICloudDriveService service,
			Handler ehandler, Handler aHandler,
			FileFolderInfo innerParent,
			FileFolderInfo shaerFileFolderInfo) {
		String info = null;
		if (ShareDriveApplication.getInstance().
				getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), aHandler);
				} catch (ClientException e1) {
					e1.printStackTrace();
					return info;
				}
			}

			try {
				service.copyFolder( shaerFileFolderInfo, innerParent);
				Message copyMsg = new Message();
				copyMsg.what = 3;
				copyMsg.obj = innerParent;
				aHandler.sendMessage(copyMsg);
				
			} catch (ClientException e) {
				handleException(ehandler, e, ClientConfig.TARGETFILESUCCESS, null);
				e.printStackTrace();
			}
		}
		return info;
	}

	public void handleException(Handler ehandler, ClientException e,
			int messageCode, Object obj) {
		// TODO Auto-generated method stub
		Message msg = new Message();
		if (null != e) {
			LogUtil.e(TAG,
					"[Exception] webservice messageCode:" + messageCode
					+ " | eStatusCode:" + e.getStatusCode()
					+ " | eCode:" + e.getCode() + " | eMsg:"+ e.getMessage());
			msg.what = e.getStatusCode();
			String code = "";
			if (null != e.getCode()) {
				code = e.getCode();
			}
			if("Sorry, Server Exception!".trim().equals(e.getMessage().trim())){
				msg.arg2 = Constant.SAVE_TO_ONEBOX_fail;
			}
			msg.arg1 = messageCode;
			msg.obj = code;
		} else {
			msg.arg1 = messageCode;
			msg.what = ExceptionConstant.access_internet_Failed;
		}
		ehandler.sendMessage(msg);
	}

	
}
